package org.tea.inventory.admin.web.admin;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.tea.inventory.admin.annotation.LoginAdmin;
import org.tea.inventory.admin.dao.Types;
import org.tea.inventory.base.util.ResponseUtil;
import org.tea.inventory.db.enums.IndustryTypeEnum;
import org.tea.inventory.db.domain.Admin;
import org.tea.inventory.db.domain.AlumniUser;
import org.tea.inventory.db.domain.News;
import org.tea.inventory.db.domain.NewsCriterion;
import org.tea.inventory.db.domain.NewsOrganize;
import org.tea.inventory.db.service.AdminService;
import org.tea.inventory.db.service.NewsOrganizeService;
import org.tea.inventory.db.service.NewsService;
import org.tea.inventory.db.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api("消息")
@RestController
@RequestMapping("/admin/news")
public class NewsController {

    @Autowired
    private NewsService newsService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private NewsOrganizeService newsOrganizeService;
    @Autowired
    private UserService userService;

    @GetMapping("mall/getNotice")
    @ApiOperation(value = "获取兑换须知")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "noticeType", value = "商品兑换须知 goodsNotice  礼品兑换须知giftNotice 积分须知integralNotice ", paramType = "query", dataType = "string")
    })
    public Object getNotice(String noticeType) {
        List<News> notice = newsService.getNotice(noticeType);
        News news = CollectionUtil.isEmpty(notice) ? new News() : notice.get(0);
        return ResponseUtil.ok(news);

    }

    /**
     * 获取 交互内容列表
     *
     * @return
     */
    @PostMapping("list")
    public Object list(@LoginAdmin Integer adminId, @RequestBody NewsCriterion newsCriterion) {

        if (adminId == null) {
            return ResponseUtil.unlogin();
        }

        News news = new News();
        news.setNewsCriterion(newsCriterion);

        List<News> lstNews = newsService.querySelective(news);
        int total = newsService.countSelective(news);

        if (StringUtils.isBlank(newsCriterion.getType())) {
            List<News> lstRemove = new ArrayList<News>();
            for (News newsTemp : lstNews) {
                if (newsTemp.getType() != null && newsTemp.getType().equals("activity")
                        && newsTemp.getActivityAuditState() != 1) {
                    lstRemove.add(newsTemp);
                }
                switch (newsTemp.getType()) {
                    case "schoolInfo":
                        newsTemp.setTitle("[校园动态]-" + newsTemp.getTitle());
                        break;
                    case "alumniInfo":
                        newsTemp.setTitle("[师生风采]-" + newsTemp.getTitle());
                        break;
                    case "activity":
                        newsTemp.setTitle("[校园活动]-" + newsTemp.getTitle());
                        break;
                    case "activityNews":
                        newsTemp.setTitle("[活动新闻]-" + newsTemp.getTitle());
                        break;
                    case "lecture":
                        newsTemp.setTitle("[讲座信息]-" + newsTemp.getTitle());
                        break;
                    case "reading":
                        newsTemp.setTitle("[悦读]-" + newsTemp.getTitle());
                        break;
                    case "notice":
                        newsTemp.setTitle("[通知公告]-" + newsTemp.getTitle());
                        break;
                    case "video":
                        newsTemp.setTitle("[公管视频]-" + newsTemp.getTitle());
                        break;
                }

                //if (newsTemp.getType().equals("schoolInfo")) {
                //    newsTemp.setTitle("[校园动态]-" + newsTemp.getTitle());
                //} else if (newsTemp.getType().equals("alumniInfo")) {
                //    newsTemp.setTitle("[师生风采]-" + newsTemp.getTitle());
                //} else if (newsTemp.getType().equals("activity")) {
                //    newsTemp.setTitle("[校园活动]-" + newsTemp.getTitle());
                //} else if (newsTemp.getType().equals("activityNews")) {
                //    newsTemp.setTitle("[活动新闻]-" + newsTemp.getTitle());
                //} else if (newsTemp.getType().equals("lecture")) {
                //    newsTemp.setTitle("[讲座信息]-" + newsTemp.getTitle());
                //} else if (newsTemp.getType().equals("reading")) {
                //    newsTemp.setTitle("[悦读]-" + newsTemp.getTitle());
                //} else if (newsTemp.getType().equals("notice")) {
                //    newsTemp.setTitle("[通知公告]-" + newsTemp.getTitle());
                //}  else if (newsTemp.getType().equals("video")) {
                //    newsTemp.setTitle("[公管视频]-" + newsTemp.getTitle());
                //}
            }

            if (lstRemove.size() > 0) {
                lstNews.removeAll(lstRemove);
                total = total - lstRemove.size();
            }
        } else if (newsCriterion.getType().equals("activity")) {
            LocalDateTime localDate = LocalDateTime.now();

            for (News newsItem : lstNews) {
                // 当前时间小于报名开始时间：报名未开始
                if (newsItem.getRegistStartDate() != null && localDate.compareTo(newsItem.getRegistStartDate()) < 0) {
                    newsItem.setActivityState("报名待开始");
                } else if (newsItem.getRegistEndDate() != null && localDate.compareTo(newsItem.getRegistEndDate()) < 0) {
                    // 当前时间小于报名截止时间：报名进行中
                    newsItem.setActivityState("报名进行中");
                } else if (newsItem.getRegistEndDate() != null && localDate.compareTo(newsItem.getRegistEndDate()) > 0
                        && newsItem.getActivityStartDate() != null && localDate.compareTo(newsItem.getActivityStartDate()) < 0) {
                    // 当前时间大于报名截止时间且小于活动开始时间：报名已截止
                    newsItem.setActivityState("报名已截止");
                } else if (newsItem.getActivityStartDate() != null && localDate.compareTo(newsItem.getActivityStartDate()) > 0
                        && newsItem.getActivityEndDate() != null && localDate.compareTo(newsItem.getActivityEndDate()) < 0) {
                    // 当前时间在活动开始时间和活动结束时间之间：活动进行中
                    newsItem.setActivityState("活动进行中");
                } else if (newsItem.getActivityEndDate() != null && localDate.compareTo(newsItem.getActivityEndDate()) > 0) {
                    // 当前时间大于活动结束时间：活动已结束
                    newsItem.setActivityState("活动已结束");
                }
            }
        }

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("total", total);
        data.put("items", lstNews);

        return ResponseUtil.ok(data);
    }

    /**
     * 获取交互内容 详情
     *
     * @return
     */
    @GetMapping("read")
    public Object read(@LoginAdmin Integer adminId, Integer id) {

        if (adminId == null) {
            return ResponseUtil.unlogin();
        }

        if (id == null) {
            return ResponseUtil.badArgument();
        }

        News news = newsService.findById(id);

        return ResponseUtil.ok(news);
    }

    /**
     * 创建交互内容
     *
     * @return
     */
    @PostMapping("create")
    public Object create(@LoginAdmin Integer adminId, @RequestBody News news) {

        if (adminId == null) {
            return ResponseUtil.unlogin();
        }

        Admin admin = adminService.findById(adminId);
        if (admin != null) {
            news.setCreator(admin.getNickname());
            news.setIsAdmin("1");//标识为管理员创建(用于另外提取以关联名字头像)

            // 根据手机号查询用户关联的微信用户id
            if (StringUtils.isNotBlank(admin.getPhone())) {
                AlumniUser alumniUser = new AlumniUser();
                alumniUser.setPhone(admin.getPhone());

                PageInfo<AlumniUser> pageInfoUser = userService.querySelective(alumniUser, 1, 10, null, null);
                List<AlumniUser> lstUser = pageInfoUser.getList();
                if (lstUser != null && lstUser.size() == 1) {
                    news.setCreatorId(lstUser.get(0).getId().toString());
                } else {
                    news.setCreatorId("1");
                }
            }
        } else {
            // 查询用户表(alumni_user)
        }

        if (news.getType().equals("activity")) {
            // 后台创建的活动默认审核通过
            news.setActivityAuditState(1);
        }

        //news.setCreatorId(String.valueOf(adminId));
        news.setCreateDate(LocalDateTime.now());
        newsService.add(news);

        if (news.getOrganizeId() != null) {
            for (int organizeId : news.getOrganizeId()) {
                NewsOrganize newsOrganize = new NewsOrganize();
                newsOrganize.setNewsId(news.getId());
                newsOrganize.setOrganizeId(organizeId);
                newsOrganize.setUserId(adminId);
                newsOrganize.setFromType("0");

                newsOrganizeService.add(newsOrganize);
            }
        }

        return ResponseUtil.ok(news);
    }

    /**
     * 更新交互内容
     *
     * @return
     */
    @PostMapping("update")
    public Object update(@LoginAdmin Integer adminId, @RequestBody News news) {

        if (adminId == null) {
            return ResponseUtil.unlogin();
        }

        Integer id = news.getId();
        if (id == null) {
            return ResponseUtil.badArgument();
        }

        newsService.updateById(news);

        newsOrganizeService.deleteByActivityId(news.getId());
        if (news.getOrganizeId() != null) {
            for (int organizeId : news.getOrganizeId()) {
                NewsOrganize newsOrganize = new NewsOrganize();
                newsOrganize.setNewsId(news.getId());
                newsOrganize.setOrganizeId(organizeId);
                newsOrganize.setFromType("1");

                newsOrganizeService.add(newsOrganize);
            }
        }

        return ResponseUtil.ok(news);
    }


    /**
     * 更新审核状态
     *
     * @return
     */
    @PostMapping("updateNewsAuth")
    public Object updateNewsAuth(@LoginAdmin Integer adminId, @RequestBody News news) {

        if (adminId == null) {
            return ResponseUtil.unlogin();
        }

        newsService.updateById(news);

        return ResponseUtil.ok(news);
    }


    /**
     * 删除交互内容
     *
     * @return
     */
    @PostMapping("delete")
    public Object delete(@LoginAdmin Integer adminId, @RequestBody News news) {

        if (adminId == null) {
            return ResponseUtil.unlogin();
        }

        Integer id = news.getId();
        if (id == null) {
            return ResponseUtil.badArgument();
        }

        newsService.deleteById(id);

        return ResponseUtil.ok();
    }

    /**
     * 批量删除交互内容
     *
     * @return
     */
    @PostMapping("deleteQuantity")
    public Object deleteQuantity(@LoginAdmin Integer adminId, String newsId) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        if (newsId == null) {
            return ResponseUtil.badArgument();
        }
        newsService.deleteQuantity(Arrays.asList(newsId.split(",")));
        return ResponseUtil.ok();
    }

    /**
     * 获取 活动关联的圈子信息
     *
     * @param adminId
     * @param newsId
     * @return
     */
    @GetMapping("listActivityOrg")
    public Object listActivityOrg(@LoginAdmin Integer adminId, int newsId) {

        if (adminId == null) {
            return ResponseUtil.unlogin();
        }

        NewsOrganize newsOrganize = new NewsOrganize();
        newsOrganize.setNewsId(newsId);
        List<NewsOrganize> lstNewsOrganize = newsOrganizeService.findNewsOrganize(newsOrganize);

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("items", lstNewsOrganize);

        return ResponseUtil.ok(data);
    }

    /**
     * 获取个人动态列表
     */
    @PostMapping("listTidings")
    public Object selectTidings(@LoginAdmin Integer adminId, @RequestParam(value = "page", defaultValue = "1") Integer page,
                                @RequestParam(value = "limit", defaultValue = "10") Integer limit, String title) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }

        PageInfo<News> pageInfo = newsService.selectTidings(page, limit, title);
        Map<String, Object> data = new HashMap<>();
        data.put("total", pageInfo.getTotal());
        data.put("items", pageInfo.getList());

        return ResponseUtil.ok(data);
    }

    // 官网新闻模块相关接口

    /**
     * 获取 官网新闻内容列表
     *
     * @return
     */
    @PostMapping("listForDGTSiteNews")
    public Object listForDGTSiteNews(@RequestBody NewsCriterion newsCriterion) {
        String type = newsCriterion.getType();
        if (StringUtils.isBlank(type) ||
                !("dgtSiteNews".equals(type) || "companyNews".equals(type)
                        || "industryInfo".equals(type) || "companyDynamic".equals(type)
                        || IndustryTypeEnum.DGTINDUSTRYNEWS.getName().equals(type)
                        || IndustryTypeEnum.HIGHTECHNOLOGY.getName().equals(type)
                        || IndustryTypeEnum.FASTEXTINCTION.getName().equals(type)
                        || IndustryTypeEnum.MANUFACTURINGINDUSTRY.getName().equals(type))) {
            return ResponseUtil.badArgumentValue();
        }

        News news = new News();
        news.setNewsCriterion(newsCriterion);

        int page = newsCriterion.getPage();
        int limit = newsCriterion.getLimit();

        List<News> lstNews = newsService.querySelective(news);
        int total = newsService.countSelective(news);
        // 如果页数超范围，PageHelper自动把pageNum变成了1，生成的sql语句limit后面只有一个参数
        if ((page - 1) * limit >= total) {
            // 此时手动设置返回空集合。
            lstNews = new ArrayList<>();
        }

        Map<String, Object> data = new HashMap<>();
        data.put("total", total);
        data.put("items", lstNews);

        return ResponseUtil.ok(data);
    }


    @PostMapping("listForDGTSiteNews.if")
    public Object listForDGTSiteNewsIf(NewsCriterion newsCriterion) {
        String type = newsCriterion.getType();
        if (StringUtils.isBlank(type) ||
                !("dgtSiteNews".equals(type) || "companyNews".equals(type)
                        || "industryInfo".equals(type) || "companyDynamic".equals(type)
                        || IndustryTypeEnum.DGTINDUSTRYNEWS.getName().equals(type)
                        || IndustryTypeEnum.HIGHTECHNOLOGY.getName().equals(type)
                        || IndustryTypeEnum.FASTEXTINCTION.getName().equals(type)
                        || IndustryTypeEnum.MANUFACTURINGINDUSTRY.getName().equals(type))) {
            return ResponseUtil.badArgumentValue();
        }

        News news = new News();
        news.setNewsCriterion(newsCriterion);

        int page = newsCriterion.getPage();
        int limit = newsCriterion.getLimit();

        List<News> lstNews = newsService.querySelective(news);
        int total = newsService.countSelective(news);
        // 如果页数超范围，PageHelper自动把pageNum变成了1，生成的sql语句limit后面只有一个参数
        if ((page - 1) * limit >= total) {
            // 此时手动设置返回空集合。
            lstNews = new ArrayList<>();
        }

        Map<String, Object> data = new HashMap<>();
        data.put("total", total);
        data.put("items", lstNews);

        return ResponseUtil.ok(data);
    }

    /**
     * 获取官网新闻内容 详情
     *
     * @return
     */
    @GetMapping("readDetailForDGTSiteNews")
    public Object readDetailForDGTSiteNews(Integer id) {
        if (id == null) {
            return ResponseUtil.badArgument();
        }

        News news = newsService.findById(id);

        return ResponseUtil.ok(news);
    }


    /**
     * 创建官网新闻内容
     *
     * @return
     */
    @PostMapping("createForDGTSiteNews")
    public Object createForDGTSiteNews(@LoginAdmin Integer adminId, @RequestBody News news) {

        if (adminId == null) {
            return ResponseUtil.unlogin();
        }

        Admin admin = adminService.findById(adminId);
        if (admin != null) {
            news.setCreator(admin.getNickname());
            news.setIsAdmin("1");//标识为管理员创建(用于另外提取以关联名字头像)

            // 根据手机号查询用户关联的微信用户id
            if (StringUtils.isNotBlank(admin.getPhone())) {
                AlumniUser alumniUser = new AlumniUser();
                alumniUser.setPhone(admin.getPhone());

                PageInfo<AlumniUser> pageInfoUser = userService.querySelective(alumniUser, 1, 10, null, null);
                List<AlumniUser> lstUser = pageInfoUser.getList();
                if (lstUser != null && lstUser.size() == 1) {
                    news.setCreatorId(lstUser.get(0).getId().toString());
                } else {
                    news.setCreatorId("1");
                }
            }
        } else {
            // 查询用户表(alumni_user)
        }

        news.setCreateDate(LocalDateTime.now());
        newsService.add(news);

        return ResponseUtil.ok(news);
    }

    @PostMapping("getdgtIndustryNews")
    public Object getdgtIndustryNews() {
        List<Types> types = new ArrayList<>();
        types.add(new Types(IndustryTypeEnum.DGTINDUSTRYNEWS.getName(), IndustryTypeEnum.DGTINDUSTRYNEWS.getContent()));
        types.add(new Types(IndustryTypeEnum.HIGHTECHNOLOGY.getName(), IndustryTypeEnum.HIGHTECHNOLOGY.getContent()));
        types.add(new Types(IndustryTypeEnum.FASTEXTINCTION.getName(), IndustryTypeEnum.FASTEXTINCTION.getContent()));
        types.add(new Types(IndustryTypeEnum.MANUFACTURINGINDUSTRY.getName(), IndustryTypeEnum.MANUFACTURINGINDUSTRY.getContent()));
        return ResponseUtil.ok(types);

    }


}
